<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        class People {
            constructor(name) {
                this.name = name
                this.events = {};
            }
            // TODO: 请在此处完善代码
            on(event, callBack) {
                let eventArr = this.events[event] || (this.events[event] = []);
                eventArr.push(callBack);
            }
            off(event, callBack) {
                let eventArr = this.events[event];
                //判断要解除的事件是否存在
                if (eventArr) {
                    //利用some，只要一解除了事件马上终止，避免过多循环。
                    eventArr.some((item, index, arr) => {
                        if (item === callBack) {
                            arr.splice(index, 1);
                            return true;
                        }
                    });
                } else {
                    console.log('你要解除的事件不存在！');
                }
            }
            emit(event, data) {
                let eventArr = this.events[event];
                //判断要触发的事件是否存在
                if (eventArr) {
                    eventArr.forEach(callBack => {
                        callBack(data);
                    })
                }else{
                    console.log('你要触发的事件不存在！');
                }
                // 遍历同事件的所有回调,执行
            }
            sayHi() {
                console.log(`Hi, I am ${this.name}`)
            }
        }


        /* 以下为测试代码 */
        const say1 = (greeting) => {
            console.log(`${greeting}, nice meeting you.`)
        }

        const say2 = (greeting) => {
            console.log(`${greeting}, nice meeting you, too.`)
        }

        const jerry = new People('Jerry')
        jerry.sayHi()
        // => 输出：'Hi, I am Jerry'

        jerry.on('greeting', say1)
        jerry.on('greeting', say2)

        jerry.emit('greeting', 'Hi')
        // => 输出：'Hi, nice meeting you.' 和 'Hi, nice meeting you, too'

        jerry.off('greeting', say1)
        jerry.emit('greeting', 'Hi')
        // => 只输出：'Hi, nice meeting you, too'
    </script>
</body>

</html>